import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
import 'package:file_picker/file_picker.dart';
import 'dart:io';

class PracticePage extends StatefulWidget {
  const PracticePage({Key? key}) : super(key: key);
  @override
  State<PracticePage> createState() => _PracticePageState();
}

class _PracticePageState extends State<PracticePage> {
  List<Map<String, dynamic>> _customQuestions = [];
  bool _useCustom = false;
  int _practiceTotal = 20;
  int _practiceDone = 0;
  int _practiceCorrect = 0;
  int _practiceWrong = 0;

  List<Map<String, dynamic>> _customPrescriptionQuestions = [];
  bool _useCustomPrescription = false;
  int _prescriptionTotal = 4;
  int _prescriptionDone = 0;
  int _prescriptionCorrect = 0;
  int _prescriptionWrong = 0;

  List<Map<String, dynamic>> _wrongPracticeQuestions = [];
  List<Map<String, dynamic>> _wrongPrescriptionQuestions = [];

  int get _currentTotal {
    if (_useCustom && _customQuestions.isNotEmpty) {
      return _customQuestions.length;
    }
    return 3; // 默认题库数量（如有扩展请同步修改）
  }

  int get _currentPrescriptionTotal {
    if (_useCustomPrescription && _customPrescriptionQuestions.isNotEmpty) {
      return _customPrescriptionQuestions.length;
    }
    return 4; // 默认处方题库数量
  }

  @override
  void initState() {
    super.initState();
    _loadAllData();
  }

  Future<void> _loadAllData() async {
    await _loadPracticeProgress();
    await _loadCustomQuestions();
    await _loadPrescriptionProgress();
    await _loadCustomPrescriptionQuestions();
    await _loadWrongQuestions();
    setState(() {});
  }

  Future<void> _loadPracticeProgress() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      _practiceDone = prefs.getInt('practice_done') ?? 0;
      _practiceCorrect = prefs.getInt('practice_correct') ?? 0;
      _practiceWrong = prefs.getInt('practice_wrong') ?? 0;
      _practiceTotal = prefs.getInt('practice_total') ?? 20;
    });
  }

  Future<void> _savePracticeProgress(int done, int correct, int wrong, int total) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setInt('practice_done', done);
    await prefs.setInt('practice_correct', correct);
    await prefs.setInt('practice_wrong', wrong);
    await prefs.setInt('practice_total', total);
    setState(() {
      _practiceDone = done;
      _practiceCorrect = correct;
      _practiceWrong = wrong;
      _practiceTotal = total;
    });
  }

  Future<void> _loadCustomQuestions() async {
    final prefs = await SharedPreferences.getInstance();
    final jsonStr = prefs.getString('custom_questions');
    if (jsonStr != null && jsonStr.isNotEmpty) {
      final list = json.decode(jsonStr);
      if (list is List) {
        setState(() {
          _customQuestions = List<Map<String, dynamic>>.from(list);
        });
      }
    }
  }

  Future<void> _saveCustomQuestions() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString('custom_questions', json.encode(_customQuestions));
  }

  Future<void> _loadPrescriptionProgress() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      _prescriptionDone = prefs.getInt('prescription_done') ?? 0;
      _prescriptionCorrect = prefs.getInt('prescription_correct') ?? 0;
      _prescriptionWrong = prefs.getInt('prescription_wrong') ?? 0;
      _prescriptionTotal = prefs.getInt('prescription_total') ?? 4;
    });
  }

  Future<void> _savePrescriptionProgress(int done, int correct, int wrong, int total) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setInt('prescription_done', done);
    await prefs.setInt('prescription_correct', correct);
    await prefs.setInt('prescription_wrong', wrong);
    await prefs.setInt('prescription_total', total);
    setState(() {
      _prescriptionDone = done;
      _prescriptionCorrect = correct;
      _prescriptionWrong = wrong;
      _prescriptionTotal = total;
    });
  }

  Future<void> _loadCustomPrescriptionQuestions() async {
    final prefs = await SharedPreferences.getInstance();
    final jsonStr = prefs.getString('custom_prescription_questions');
    if (jsonStr != null && jsonStr.isNotEmpty) {
      final list = json.decode(jsonStr);
      if (list is List) {
        setState(() {
          _customPrescriptionQuestions = List<Map<String, dynamic>>.from(list);
        });
      }
    }
  }

  Future<void> _saveCustomPrescriptionQuestions() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString('custom_prescription_questions', json.encode(_customPrescriptionQuestions));
  }

  Future<void> _loadWrongQuestions() async {
    final prefs = await SharedPreferences.getInstance();
    final wrong1 = prefs.getString('wrong_practice_questions');
    final wrong2 = prefs.getString('wrong_prescription_questions');
    setState(() {
      _wrongPracticeQuestions = [];
      _wrongPrescriptionQuestions = [];
      if (wrong1 != null && wrong1.isNotEmpty) {
        final list = json.decode(wrong1);
        if (list is List) {
          _wrongPracticeQuestions = List<Map<String, dynamic>>.from(list);
        }
      }
      if (wrong2 != null && wrong2.isNotEmpty) {
        final list = json.decode(wrong2);
        if (list is List) {
          _wrongPrescriptionQuestions = List<Map<String, dynamic>>.from(list);
        }
      }
    });
  }

  Future<void> _saveWrongQuestions() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString('wrong_practice_questions', json.encode(_wrongPracticeQuestions));
    await prefs.setString('wrong_prescription_questions', json.encode(_wrongPrescriptionQuestions));
  }

  void _addWrongPracticeQuestion(Map<String, dynamic> q) {
    setState(() {
      if (!_wrongPracticeQuestions.any((e) => e['question'] == q['question'] && e['answer'] == q['answer'])) {
        _wrongPracticeQuestions.add(q);
        _saveWrongQuestions();
      }
    });
  }
  void _addWrongPrescriptionQuestion(Map<String, dynamic> q) {
    setState(() {
      if (!_wrongPrescriptionQuestions.any((e) => e['question'] == q['question'] && e['answer'] == q['answer'])) {
        _wrongPrescriptionQuestions.add(q);
        _saveWrongQuestions();
      }
    });
  }
  void _removeWrongPracticeQuestion(int idx) {
    setState(() {
      _wrongPracticeQuestions.removeAt(idx);
      _saveWrongQuestions();
    });
  }
  void _removeWrongPrescriptionQuestion(int idx) {
    setState(() {
      _wrongPrescriptionQuestions.removeAt(idx);
      _saveWrongQuestions();
    });
  }

  void _showCustomQuestionDialog(BuildContext context) {
    final qController = TextEditingController();
    final aController = TextEditingController();
    final optsController = TextEditingController();
    final analysisController = TextEditingController();
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('添加自定义题目'),
        content: SingleChildScrollView(
          child: Column(
            children: [
              TextField(controller: qController, decoration: const InputDecoration(labelText: '题目')), 
              TextField(controller: optsController, decoration: const InputDecoration(labelText: '选项（用|分隔）')), 
              TextField(controller: aController, decoration: const InputDecoration(labelText: '正确答案')), 
              TextField(controller: analysisController, decoration: const InputDecoration(labelText: '解析')), 
            ],
          ),
        ),
        actions: [
          TextButton(onPressed: () => Navigator.pop(ctx), child: const Text('取消')),
          TextButton(onPressed: () {
            if (qController.text.isNotEmpty && optsController.text.isNotEmpty && aController.text.isNotEmpty) {
              setState(() {
                _customQuestions.add({
                  'question': qController.text,
                  'options': optsController.text.split('|'),
                  'answer': aController.text,
                  'analysis': analysisController.text,
                });
              });
              _saveCustomQuestions();
              Navigator.pop(ctx);
            }
          }, child: const Text('保存')),
        ],
      ),
    );
  }

  Future<void> _importCustomQuestions() async {
    final result = await FilePicker.platform.pickFiles(type: FileType.custom, allowedExtensions: ['json']);
    if (result != null && result.files.single.path != null) {
      final file = result.files.single;
      try {
        final content = await File(file.path!).readAsString();
        final list = json.decode(content);
        if (list is List) {
          setState(() {
            _customQuestions = List<Map<String, dynamic>>.from(list);
          });
          await _saveCustomQuestions();
          ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('自定义题库导入成功')));
        } else {
          ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('导入文件格式错误')));
        }
      } catch (e) {
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('导入失败: $e')));
      }
    }
  }

  void _showCustomPrescriptionQuestionDialog(BuildContext context) {
    final qController = TextEditingController();
    final aController = TextEditingController();
    final optsController = TextEditingController();
    final analysisController = TextEditingController();
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('添加处方自定义题目'),
        content: SingleChildScrollView(
          child: Column(
            children: [
              TextField(controller: qController, decoration: const InputDecoration(labelText: '题目')), 
              TextField(controller: optsController, decoration: const InputDecoration(labelText: '选项（用|分隔）')), 
              TextField(controller: aController, decoration: const InputDecoration(labelText: '正确答案')), 
              TextField(controller: analysisController, decoration: const InputDecoration(labelText: '解析')), 
            ],
          ),
        ),
        actions: [
          TextButton(onPressed: () => Navigator.pop(ctx), child: const Text('取消')),
          TextButton(onPressed: () {
            if (qController.text.isNotEmpty && optsController.text.isNotEmpty && aController.text.isNotEmpty) {
              setState(() {
                _customPrescriptionQuestions.add({
                  'question': qController.text,
                  'options': optsController.text.split('|'),
                  'answer': aController.text,
                  'analysis': analysisController.text,
                });
              });
              _saveCustomPrescriptionQuestions();
              Navigator.pop(ctx);
            }
          }, child: const Text('保存')),
        ],
      ),
    );
  }

  Future<void> _importCustomPrescriptionQuestions() async {
    final result = await FilePicker.platform.pickFiles(type: FileType.custom, allowedExtensions: ['json']);
    if (result != null && result.files.single.path != null) {
      final file = result.files.single;
      try {
        final content = await File(file.path!).readAsString();
        final list = json.decode(content);
        if (list is List) {
          setState(() {
            _customPrescriptionQuestions = List<Map<String, dynamic>>.from(list);
          });
          await _saveCustomPrescriptionQuestions();
          ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('处方自定义题库导入成功')));
        } else {
          ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('导入文件格式错误')));
        }
      } catch (e) {
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('导入失败: $e')));
      }
    }
  }

  void _startPractice(BuildContext context) async {
    final questions = _useCustom && _customQuestions.isNotEmpty ? _customQuestions : null;
    final total = _currentTotal;
    if (_practiceDone >= total && total > 0) {
      await _savePracticeProgress(0, 0, 0, total);
    }
    final result = await Navigator.of(context).push(
      MaterialPageRoute(
        builder: (_) => PracticeQuizPage(
          questions: questions,
          onProgress: (done, correct, wrong) => _savePracticeProgress(done, correct, wrong, total),
          initialDone: _practiceDone >= total ? 0 : _practiceDone,
          initialCorrect: _practiceDone >= total ? 0 : _practiceCorrect,
          initialWrong: _practiceDone >= total ? 0 : _practiceWrong,
          onAddWrong: _addWrongPracticeQuestion,
        ),
      ),
    );
    if (result == true) {
      _loadPracticeProgress();
      await _loadWrongQuestions();
      setState(() {});
    }
  }

  void _startPrescriptionPractice(BuildContext context) async {
    final questions = _useCustomPrescription && _customPrescriptionQuestions.isNotEmpty ? _customPrescriptionQuestions : null;
    final total = _currentPrescriptionTotal;
    if (_prescriptionDone >= total && total > 0) {
      await _savePrescriptionProgress(0, 0, 0, total);
    }
    final result = await Navigator.of(context).push(
      MaterialPageRoute(
        builder: (_) => PrescriptionPracticePage(
          questions: questions,
          onProgress: (done, correct, wrong) => _savePrescriptionProgress(done, correct, wrong, total),
          initialDone: _prescriptionDone >= total ? 0 : _prescriptionDone,
          initialCorrect: _prescriptionDone >= total ? 0 : _prescriptionCorrect,
          initialWrong: _prescriptionDone >= total ? 0 : _prescriptionWrong,
          onAddWrong: _addWrongPrescriptionQuestion,
        ),
      ),
    );
    if (result == true) {
      _loadPrescriptionProgress();
      await _loadWrongQuestions();
      setState(() {});
    }
  }

  void _startWrongPracticeReview(BuildContext context) async {
    await Navigator.of(context).push(
      MaterialPageRoute(builder: (_) => WrongReviewPage(
        questions: List<Map<String, dynamic>>.from(_wrongPracticeQuestions),
        onRemove: (idx) => _removeWrongPracticeQuestion(idx),
        title: '辨证错题复习',
      )),
    );
    await _loadWrongQuestions();
    setState(() {});
  }
  void _startWrongPrescriptionReview(BuildContext context) async {
    await Navigator.of(context).push(
      MaterialPageRoute(builder: (_) => WrongReviewPage(
        questions: List<Map<String, dynamic>>.from(_wrongPrescriptionQuestions),
        onRemove: (idx) => _removeWrongPrescriptionQuestion(idx),
        title: '处方错题复习',
      )),
    );
    await _loadWrongQuestions();
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    // 动态获取错题数量，保证UI刷新
    final wrongPracticeCount = _wrongPracticeQuestions.length;
    final wrongPrescriptionCount = _wrongPrescriptionQuestions.length;
    return Scaffold(
      appBar: AppBar(
        title: const Text('辨证练习'),
        backgroundColor: Colors.brown[50],
        elevation: 0,
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 练习模式
              Row(
                children: [
                  Expanded(
                    child: _PracticeModeCard(
                      icon: Icons.play_circle_outline,
                      title: '辨证练习',
                      desc: '基础六经辨证与进阶练习',
                      color: Colors.brown,
                      buttonText: '开始练习',
                      onPressed: () => _startPractice(context),
                      extraActions: [
                        IconButton(
                          icon: Icon(Icons.library_add, color: Colors.brown),
                          tooltip: '自定义题库',
                          onPressed: () => _showCustomQuestionDialog(context),
                        ),
                        IconButton(
                          icon: Icon(Icons.file_upload, color: Colors.brown),
                          tooltip: '导入题库',
                          onPressed: _importCustomQuestions,
                        ),
                        Switch(
                          value: _useCustom,
                          onChanged: (v) => setState(() => _useCustom = v),
                          activeColor: Colors.brown,
                        ),
                        const Padding(
                          padding: EdgeInsets.only(right: 8),
                          child: Center(child: Text('自定义', style: TextStyle(color: Colors.brown))),
                        ),
                      ],
                    ),
                  ),
                  const SizedBox(width: 16),
                  Expanded(
                    child: _PracticeModeCard(
                      icon: Icons.send,
                      title: '处方练习',
                      desc: '模拟处方组合与处方选择',
                      color: Colors.teal,
                      buttonText: '开始练习',
                      onPressed: () => _startPrescriptionPractice(context),
                      extraActions: [
                        IconButton(
                          icon: Icon(Icons.library_add, color: Colors.teal),
                          tooltip: '处方自定义题库',
                          onPressed: () => _showCustomPrescriptionQuestionDialog(context),
                        ),
                        IconButton(
                          icon: Icon(Icons.file_upload, color: Colors.teal),
                          tooltip: '导入处方题库',
                          onPressed: _importCustomPrescriptionQuestions,
                        ),
                        Switch(
                          value: _useCustomPrescription,
                          onChanged: (v) => setState(() => _useCustomPrescription = v),
                          activeColor: Colors.teal,
                        ),
                        const Padding(
                          padding: EdgeInsets.only(right: 8),
                          child: Center(child: Text('自定义', style: TextStyle(color: Colors.teal))),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 24),
              // 练习进度
              Container(
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: Colors.brown[50],
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text('练习进度', style: TextStyle(fontWeight: FontWeight.bold, color: Colors.brown)),
                    const SizedBox(height: 12),
                    Row(
                      children: [
                        const Text('辨证练习进度', style: TextStyle(color: Colors.brown)),
                        const SizedBox(width: 8),
                        Expanded(
                          child: LinearProgressIndicator(
                            value: _currentTotal == 0 ? 0 : _practiceDone / _currentTotal,
                            minHeight: 8,
                            backgroundColor: Colors.brown.withOpacity(0.1),
                            valueColor: AlwaysStoppedAnimation<Color>(Colors.brown),
                          ),
                        ),
                        const SizedBox(width: 8),
                        Text('$_practiceDone/$_currentTotal题'),
                        const SizedBox(width: 8),
                        ElevatedButton(
                          onPressed: _currentTotal == 0 ? null : () => _startPractice(context),
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.brown,
                            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
                          ),
                          child: const Text('继续练习', style: TextStyle(color: Colors.black)),
                        ),
                      ],
                    ),
                    const SizedBox(height: 8),
                    Row(
                      children: [
                        Text('正确：$_practiceCorrect', style: const TextStyle(color: Colors.green)),
                        const SizedBox(width: 16),
                        Text('错误：$_practiceWrong', style: const TextStyle(color: Colors.red)),
                      ],
                    ),
                    const SizedBox(height: 16),
                    // 处方练习进度
                    Row(
                      children: [
                        const Text('处方练习进度', style: TextStyle(color: Colors.teal)),
                        const SizedBox(width: 8),
                        Expanded(
                          child: LinearProgressIndicator(
                            value: _currentPrescriptionTotal == 0 ? 0 : _prescriptionDone / _currentPrescriptionTotal,
                            minHeight: 8,
                            backgroundColor: Colors.teal.withOpacity(0.1),
                            valueColor: AlwaysStoppedAnimation<Color>(Colors.teal),
                          ),
                        ),
                        const SizedBox(width: 8),
                        Text('$_prescriptionDone/$_currentPrescriptionTotal题'),
                        const SizedBox(width: 8),
                        ElevatedButton(
                          onPressed: _currentPrescriptionTotal == 0 ? null : () => _startPrescriptionPractice(context),
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.teal,
                            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
                          ),
                          child: const Text('继续练习', style: TextStyle(color: Colors.black)),
                        ),
                      ],
                    ),
                    const SizedBox(height: 8),
                    Row(
                      children: [
                        Text('正确：$_prescriptionCorrect', style: const TextStyle(color: Colors.green)),
                        const SizedBox(width: 16),
                        Text('错误：$_prescriptionWrong', style: const TextStyle(color: Colors.red)),
                      ],
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 24),
              // 错题复习
              const Text('错题复习', style: TextStyle(fontWeight: FontWeight.bold, color: Colors.brown)),
              const SizedBox(height: 12),
              Row(
                children: [
                  Expanded(
                    child: GestureDetector(
                      onTap: wrongPracticeCount > 0 ? () => _startWrongPracticeReview(context) : null,
                      child: _WrongReviewCard(label: '辨证', count: wrongPracticeCount, color: Colors.brown[100]!),
                    ),
                  ),
                  const SizedBox(width: 8),
                  Expanded(
                    child: GestureDetector(
                      onTap: wrongPrescriptionCount > 0 ? () => _startWrongPrescriptionReview(context) : null,
                      child: _WrongReviewCard(label: '处方', count: wrongPrescriptionCount, color: Colors.teal[100]!),
                    ),
                  ),
                  const SizedBox(width: 8),
                  Expanded(
                    child: ElevatedButton(
                      onPressed: (wrongPracticeCount > 0 || wrongPrescriptionCount > 0)
                        ? () {
                            if (wrongPracticeCount > 0 && wrongPrescriptionCount > 0) {
                              showModalBottomSheet(
                                context: context,
                                builder: (ctx) => Column(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    ListTile(
                                      title: const Text('辨证错题复习'),
                                      onTap: () {
                                        Navigator.pop(ctx);
                                        _startWrongPracticeReview(context);
                                      },
                                    ),
                                    ListTile(
                                      title: const Text('处方错题复习'),
                                      onTap: () {
                                        Navigator.pop(ctx);
                                        _startWrongPrescriptionReview(context);
                                      },
                                    ),
                                  ],
                                ),
                              );
                            } else if (wrongPracticeCount > 0) {
                              _startWrongPracticeReview(context);
                            } else if (wrongPrescriptionCount > 0) {
                              _startWrongPrescriptionReview(context);
                            }
                          }
                        : null,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.brown,
                        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
                      ),
                      child: const Text('开始复习', style: TextStyle(color: Colors.black)),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class _PracticeModeCard extends StatelessWidget {
  final IconData icon;
  final String title;
  final String desc;
  final Color color;
  final String buttonText;
  final VoidCallback? onPressed;
  final List<Widget>? extraActions;
  const _PracticeModeCard({required this.icon, required this.title, required this.desc, required this.color, required this.buttonText, this.onPressed, this.extraActions});

  @override
  Widget build(BuildContext context) {
    return Card(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
      elevation: 2,
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            Icon(icon, size: 36, color: color),
            const SizedBox(height: 8),
            Text(title, style: TextStyle(fontWeight: FontWeight.bold, color: color)),
            const SizedBox(height: 8),
            Text(desc, style: const TextStyle(fontSize: 13)),
            const SizedBox(height: 12),
            ElevatedButton(
              onPressed: onPressed,
              style: ElevatedButton.styleFrom(
                backgroundColor: color,
                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
              ),
              child: Text(buttonText, style: const TextStyle(color: Colors.black)),
            ),
            if (extraActions != null)
              ...extraActions!,
          ],
        ),
      ),
    );
  }
}

class _WrongReviewCard extends StatelessWidget {
  final String label;
  final int count;
  final Color color;
  const _WrongReviewCard({required this.label, required this.count, required this.color});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 20),
      decoration: BoxDecoration(
        color: color,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        children: [
          Text('$count', style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 20)),
          const SizedBox(height: 4),
          Text(label, style: const TextStyle(fontSize: 13)),
        ],
      ),
    );
  }
}

class PracticeQuizPage extends StatefulWidget {
  final List<Map<String, dynamic>>? questions;
  final void Function(int done, int correct, int wrong)? onProgress;
  final int initialDone;
  final int initialCorrect;
  final int initialWrong;
  final void Function(Map<String, dynamic> q)? onAddWrong;
  const PracticeQuizPage({Key? key, this.questions, this.onProgress, this.initialDone = 0, this.initialCorrect = 0, this.initialWrong = 0, this.onAddWrong}) : super(key: key);
  @override
  State<PracticeQuizPage> createState() => _PracticeQuizPageState();
}

class _PracticeQuizPageState extends State<PracticeQuizPage> {
  late final List<Map<String, dynamic>> _questions;
  int _current = 0;
  String? _selected;
  bool _showResult = false;
  int _correct = 0;
  int _wrong = 0;

  @override
  void initState() {
    super.initState();
    _questions = widget.questions ?? [
      {
        'question': '患者发热、咳嗽、恶寒、无汗、脉浮紧，最可能属于哪一经？',
        'options': ['太阳经', '阳明经', '少阳经', '太阴经'],
        'answer': '太阳经',
        'analysis': '典型太阳表实证，见于麻黄汤证。'
      },
      {
        'question': '患者高热不退，口渴欲饮，大便秘结，脉洪数，最可能属于哪一经？',
        'options': ['阳明经', '少阴经', '厥阴经', '太阳经'],
        'answer': '阳明经',
        'analysis': '阳明腑实证，见于白虎承气汤证。'
      },
      {
        'question': '患者胸胁苦满，口苦咽干，目眩，最适合的代表方剂是？',
        'options': ['小柴胡汤', '麻黄汤', '白虎汤', '理中汤'],
        'answer': '小柴胡汤',
        'analysis': '少阳病主方为小柴胡汤。'
      },
    ];
    _current = widget.initialDone;
    _correct = widget.initialCorrect;
    _wrong = widget.initialWrong;
  }

  void _submit() {
    setState(() {
      _showResult = true;
      if (_selected == _questions[_current]['answer']) {
        _correct++;
      } else {
        _wrong++;
        if (widget.onAddWrong != null) {
          widget.onAddWrong!(_questions[_current]);
        }
      }
      widget.onProgress?.call(_current + 1, _correct, _wrong);
    });
  }

  void _next() {
    setState(() {
      _current++;
      _selected = null;
      _showResult = false;
    });
    widget.onProgress?.call(_current, _correct, _wrong);
  }

  @override
  Widget build(BuildContext context) {
    if (_current >= _questions.length) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        widget.onProgress?.call(_questions.length, _correct, _wrong);
        Navigator.of(context).pop(true);
      });
      return const SizedBox.shrink();
    }
    final q = _questions[_current];
    return Scaffold(
      appBar: AppBar(
        title: const Text('辨证练习'),
        backgroundColor: Colors.brown[50],
        elevation: 0,
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('第${_current + 1}/${_questions.length}题', style: const TextStyle(color: Colors.brown)),
            const SizedBox(height: 16),
            Text(q['question'], style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16)),
            const SizedBox(height: 24),
            ...List.generate(q['options'].length, (i) {
              final opt = q['options'][i];
              return RadioListTile<String>(
                value: opt,
                groupValue: _selected,
                onChanged: _showResult ? null : (v) => setState(() => _selected = v),
                title: Text(opt),
              );
            }),
            const SizedBox(height: 24),
            if (!_showResult)
              ElevatedButton(
                onPressed: _selected == null ? null : _submit,
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.brown,
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
                ),
                child: const Text('提交', style: TextStyle(color: Colors.black)),
              ),
            if (_showResult)
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    _selected == q['answer'] ? '回答正确！' : '回答错误',
                    style: TextStyle(
                      color: _selected == q['answer'] ? Colors.green : Colors.red,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 8),
                  Text('正确答案：${q['answer']}', style: const TextStyle(color: Colors.brown)),
                  Text('解析：${q['analysis']}', style: const TextStyle(color: Colors.brown)),
                  const SizedBox(height: 16),
                  if (_current < _questions.length - 1)
                    ElevatedButton(
                      onPressed: _next,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.brown,
                        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
                      ),
                      child: const Text('下一题', style: TextStyle(color: Colors.black)),
                    )
                  else
                    const Text('练习已完成', style: TextStyle(color: Colors.brown)),
                ],
              ),
          ],
        ),
      ),
    );
  }
}

class PrescriptionPracticePage extends StatefulWidget {
  final List<Map<String, dynamic>>? questions;
  final void Function(int done, int correct, int wrong)? onProgress;
  final int initialDone;
  final int initialCorrect;
  final int initialWrong;
  final void Function(Map<String, dynamic> q)? onAddWrong;
  const PrescriptionPracticePage({Key? key, this.questions, this.onProgress, this.initialDone = 0, this.initialCorrect = 0, this.initialWrong = 0, this.onAddWrong}) : super(key: key);
  @override
  State<PrescriptionPracticePage> createState() => _PrescriptionPracticePageState();
}

class _PrescriptionPracticePageState extends State<PrescriptionPracticePage> {
  late final List<Map<String, dynamic>> _questions;
  int _current = 0;
  String? _selected;
  bool _showResult = false;
  int _correct = 0;
  int _wrong = 0;

  @override
  void initState() {
    super.initState();
    _questions = widget.questions ?? [
      {
        'question': '患者高热、大汗、口渴、脉洪大，最适合的代表方剂是？',
        'options': ['白虎汤', '小柴胡汤', '麻黄汤', '四逆汤'],
        'answer': '白虎汤',
        'analysis': '白虎汤主治阳明经实热证。'
      },
      {
        'question': '患者恶寒发热、无汗、脉浮紧，最适合的代表方剂是？',
        'options': ['麻黄汤', '桂枝汤', '小青龙汤', '大承气汤'],
        'answer': '麻黄汤',
        'analysis': '麻黄汤主治太阳表实证。'
      },
      {
        'question': '患者胸胁苦满、口苦咽干、目眩，最适合的代表方剂是？',
        'options': ['小柴胡汤', '白虎汤', '理中汤', '真武汤'],
        'answer': '小柴胡汤',
        'analysis': '小柴胡汤主治少阳病。'
      },
      {
        'question': '患者腹满而吐、食不下、自利、时腹自痛，最适合的代表方剂是？',
        'options': ['理中汤', '四逆汤', '白虎汤', '小柴胡汤'],
        'answer': '理中汤',
        'analysis': '理中汤主治太阴虚寒证。'
      },
    ];
    _current = widget.initialDone;
    _correct = widget.initialCorrect;
    _wrong = widget.initialWrong;
  }

  void _submit() {
    setState(() {
      _showResult = true;
      if (_selected == _questions[_current]['answer']) {
        _correct++;
      } else {
        _wrong++;
        if (widget.onAddWrong != null) {
          widget.onAddWrong!(_questions[_current]);
        }
      }
      widget.onProgress?.call(_current + 1, _correct, _wrong);
    });
  }

  void _next() {
    setState(() {
      _current++;
      _selected = null;
      _showResult = false;
    });
    widget.onProgress?.call(_current, _correct, _wrong);
  }

  @override
  Widget build(BuildContext context) {
    if (_current >= _questions.length) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        widget.onProgress?.call(_questions.length, _correct, _wrong);
        Navigator.of(context).pop(true);
      });
      return const SizedBox.shrink();
    }
    final q = _questions[_current];
    return Scaffold(
      appBar: AppBar(
        title: const Text('处方练习'),
        backgroundColor: Colors.teal[50],
        elevation: 0,
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('第${_current + 1}/${_questions.length}题', style: const TextStyle(color: Colors.teal)),
            const SizedBox(height: 16),
            Text(q['question'], style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16)),
            const SizedBox(height: 24),
            ...List.generate(q['options'].length, (i) {
              final opt = q['options'][i];
              return RadioListTile<String>(
                value: opt,
                groupValue: _selected,
                onChanged: _showResult ? null : (v) => setState(() => _selected = v),
                title: Text(opt),
              );
            }),
            const SizedBox(height: 24),
            if (!_showResult)
              ElevatedButton(
                onPressed: _selected == null ? null : _submit,
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.teal,
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
                ),
                child: const Text('提交', style: TextStyle(color: Colors.black)),
              ),
            if (_showResult)
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    _selected == q['answer'] ? '回答正确！' : '回答错误',
                    style: TextStyle(
                      color: _selected == q['answer'] ? Colors.green : Colors.red,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 8),
                  Text('正确答案：${q['answer']}', style: const TextStyle(color: Colors.teal)),
                  Text('解析：${q['analysis']}', style: const TextStyle(color: Colors.teal)),
                  const SizedBox(height: 16),
                  if (_current < _questions.length - 1)
                    ElevatedButton(
                      onPressed: _next,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.teal,
                        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
                      ),
                      child: const Text('下一题', style: TextStyle(color: Colors.black)),
                    )
                  else
                    const Text('练习已完成', style: TextStyle(color: Colors.teal)),
                ],
              ),
          ],
        ),
      ),
    );
  }
}

class WrongReviewPage extends StatefulWidget {
  final List<Map<String, dynamic>> questions;
  final void Function(int idx) onRemove;
  final String title;
  const WrongReviewPage({Key? key, required this.questions, required this.onRemove, required this.title}) : super(key: key);
  @override
  State<WrongReviewPage> createState() => _WrongReviewPageState();
}

class _WrongReviewPageState extends State<WrongReviewPage> {
  int _current = 0;
  @override
  Widget build(BuildContext context) {
    if (widget.questions.isEmpty) {
      return Scaffold(
        appBar: AppBar(title: Text(widget.title)),
        body: const Center(child: Text('暂无错题')),);
    }
    final q = widget.questions[_current];
    return Scaffold(
      appBar: AppBar(title: Text(widget.title)),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('第${_current + 1}/${widget.questions.length}题', style: const TextStyle(color: Colors.brown)),
            const SizedBox(height: 16),
            Text(q['question'], style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16)),
            const SizedBox(height: 24),
            ...List.generate((q['options'] as List).length, (i) {
              final opt = q['options'][i];
              return ListTile(
                title: Text(opt),
                leading: Radio<String>(
                  value: opt,
                  groupValue: q['answer'],
                  onChanged: null,
                ),
                trailing: opt == q['answer'] ? const Icon(Icons.check, color: Colors.green) : null,
              );
            }),
            const SizedBox(height: 24),
            Text('正确答案：${q['answer']}', style: const TextStyle(color: Colors.brown)),
            Text('解析：${q['analysis']}', style: const TextStyle(color: Colors.brown)),
            const SizedBox(height: 16),
            Row(
              children: [
                if (_current < widget.questions.length - 1)
                  ElevatedButton(
                    onPressed: () => setState(() => _current++),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.brown,
                      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
                    ),
                    child: const Text('下一题', style: TextStyle(color: Colors.black)),
                  ),
                if (widget.questions.length > 1)
                  const SizedBox(width: 16),
                ElevatedButton(
                  onPressed: () {
                    widget.onRemove(_current);
                    if (_current >= widget.questions.length - 1) {
                      Navigator.of(context).pop();
                    } else {
                      setState(() {});
                    }
                  },
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.red[100],
                    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
                  ),
                  child: const Text('移除错题', style: TextStyle(color: Colors.red)),
                ),
              ],
            ),
            if (_current >= widget.questions.length - 1 && widget.questions.length == 1)
              const Padding(
                padding: EdgeInsets.only(top: 24),
                child: Text('错题已全部复习', style: TextStyle(color: Colors.green)),
              ),
          ],
        ),
      ),
    );
  }
} 